package cn.com.surker.maps;

import cn.com.surker.common.HttpRequestHelper;
import cn.com.surker.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lucky
 * @create 2022年04月25 10:11
 * @desc
 */
@Slf4j
public class IbsMaps {

    /**高德地图APIKEY***/
    public static String apiKey = "b337a3b7fadbe5910fecfe31ec96f3ec";
    public static void main(String[] args){
        System.out.println(IbsMaps.routeTruck("106.259486,29.348463", "106.280043,29.391437", 1));
    }

    /**
     * 小型客车路线规划
     * @param origin 起点坐标(经度,纬度 lng,lat)
     * @param destination 终点坐标(经度,纬度 lng,lat)
     * @param strategy 1：微型车，2：轻型车（默认值），3：中型车，4：重型车
     * @return
     */
    public static Map<String, Object> routeTruck(String origin, String destination, Integer strategy) {
        String url = "https://restapi.amap.com/v3/direction/driving?" +
                "key=" + apiKey + "&origin=" + origin + "&destination=" +destination
                + "&strategy=" + strategy;
        try {
            String result = HttpRequestHelper.get(url);
            JSONObject content = JSONObject.parseObject(result);
            System.out.println(content);
            if (StringUtils.isNull(content) ||content.getInteger("status") != 1)
                return null;
//            JSONObject data = content.getJSONObject("route");
//            if (data == null)
//                return null;
            /**路线JSON**/
            JSONObject route = content.getJSONObject("route");
            if (route == null)
                return null;
            JSONArray paths = route.getJSONArray("paths");
            if (paths == null || paths.size() == 0)
                return null;
            /**取最优路线**/
            JSONObject obj = paths.getJSONObject(0);
            if (obj == null)
                return null;

            Map<String, Object> map = new HashMap<>();
            /**行驶距离**/
            map.put("distance", obj.getString("distance"));
            /**预计时间**/
            map.put("duration", obj.getString("duration"));
            /**线路规划策略**/
            map.put("policy", obj.getString("strategy"));

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 货车路线规划
     * @param origin 起点坐标(经度,纬度 lng,lat)
     * @param destination 终点坐标(经度,纬度 lng,lat)
     * @param size 1：微型车，2：轻型车（默认值），3：中型车，4：重型车
     * @return
     */
    public static Map<String, Object> routeDirectionTruck(String origin, String destination, Integer size, Integer strategy) {
        if (StringUtils.isNull(size))
            size = 3;
        if (StringUtils.isNull(strategy))
            size = 1;
        String url = "https://restapi.amap.com/v4/direction/truck?" +
                "key=" + apiKey + "&origin=" + origin + "&destination=" +destination
                + "&size=" + size + "&strategy=" + strategy;
        try {
            String result = HttpRequestHelper.get(url);
            JSONObject content = JSONObject.parseObject(result);
            System.out.println(content);
            if (StringUtils.isNull(content) ||content.getInteger("errcode") != 0)
                return null;
            JSONObject data = content.getJSONObject("data");
            if (data == null)
                return null;
            /**路线JSON**/
            JSONObject route = data.getJSONObject("route");
            if (route == null)
                return null;
            JSONArray paths = route.getJSONArray("paths");
            if (paths == null || paths.size() == 0)
                return null;
            /**取最优路线**/
            JSONObject obj = paths.getJSONObject(0);
            if (obj == null)
                return null;

            Map<String, Object> map = new HashMap<>();
            /**行驶距离**/
            map.put("distance", obj.getString("distance"));
            /**预计时间**/
            map.put("duration", obj.getString("duration"));
            /**线路规划策略**/
            map.put("policy", obj.getString("strategy"));

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


	/**
	 * 查询高德地图坐标点周把的地理位置(仅查询公司类型的地址)
	 * @param lng					经度
	 * @param lat					纬度
	 * @param radius				距离坐标中心点距离(默认100)
	 * @param keywords				关键字
	 * @return						返回坐标点
	 */
    public static List<Map<String,Object>> amapAround(String lng, String lat, Integer radius,List<String> types, String... keywords) throws URISyntaxException, MalformedURLException {
    	if(StringUtils.isBlank(lng) || StringUtils.isBlank(lat)){
    		return null;
		}
    	if(radius == null){
    		radius = 100;
		}
    	if (types == null || types.isEmpty() && (keywords == null || keywords.length < 1)){
    		types = new ArrayList<>();
    		types.add("10000");
			types.add("20000");
			types.add("30000");
			types.add("40000");
			types.add("50000");
			types.add("60000");
			types.add("70000");
			types.add("80000");
			types.add("90000");
			types.add("100000");
			types.add("110000");
			types.add("120000");
			types.add("130000");
			types.add("140000");
			types.add("150000");
			types.add("160000");
			types.add("170000");
			types.add("180000");
			types.add("190000");
			types.add("200000");
			types.add("220000");
			types.add("970000");
			types.add("990000");
		}
    	//	拼凑经纬度信息
    	String location = lng + "," + lat;
		String url = "https://restapi.amap.com/v3/place/around?key=" + apiKey + "&location=" + location + "&radius=" + radius;
		String typesStr = "";
		for(int i = 0,s = types.size();i < s;i++){
			String ts = types.get(i);
			if(i != 0){
				typesStr += "|";
			}else {
				typesStr = "&types=";
			}
			typesStr += ts;
		}
		url += typesStr;
		if(keywords != null || keywords.length > 0){
			//	添加关键字参数
			String kps = "";
			for(int i = 0,s = keywords.length;i < s;i++){
				String kw = keywords[i];
				if(StringUtils.isNotBlank(kw)){
					if(i != 0){
						kps += "|";
					}
					kps += kw;
				}
			}
			url += "&keywords=" + kps;
		}
		List<Map<String,Object>> poiList = new ArrayList<>();
		//	请求地图api
		URL urlO = new URL(url);
		URI uri = new URI(urlO.getProtocol(), urlO.getHost(), urlO.getPath(), urlO.getQuery(), null);
		String resStr = HttpRequestHelper.get(uri);
		if(resStr != null){
			JSONObject jsonObject = JSONObject.parseObject(resStr);
			String status = jsonObject.getString("status");
			if("1".equals(status)){
				// 表示请求成功
				JSONArray JApois = jsonObject.getJSONArray("pois");
				for (int i = 0,s = JApois.size();i < s;i++){
					try {
						JSONObject poi = JApois.getJSONObject(i);
						//	地点坐标点
						String poiLoc = poi.getString("location");
						// 格式化为经纬度信息
						String[] poiLocArr = poiLoc.split(",");
						String poiLng = poiLocArr[0];
						String poiLat = poiLocArr[1];
						//	公司名
						String name = poi.getString("name");
						//	坐标地址
						String pname = poi.getString("pname");
						String cityname = poi.getString("cityname");
						String adname = poi.getString("adname");
						String address = poi.getString("address");
						// 详细地址
						String addrDetail = pname + cityname + adname + address;
						Map<String,Object> poiMap = new HashMap<>();
						poiMap.put("lng",poiLng);
						poiMap.put("lat",poiLat);
						poiMap.put("name",name);
						poiMap.put("address",addrDetail);
						poiList.add(poiMap);
					} catch (Exception e) {
						log.error("格式化高德地图POI出错:");
						e.printStackTrace();
						continue;
					}
				}
			}
		}
    	return poiList;
	}

	public static List<Map<String, Object>> amapKeyword(String keyword) throws MalformedURLException, URISyntaxException {
		if(StringUtils.isBlank(keyword)){
			return null;
		}
		List<String> types = new ArrayList<>();
		types.add("10000");
		types.add("20000");
		types.add("30000");
		types.add("40000");
		types.add("50000");
		types.add("60000");
		types.add("70000");
		types.add("80000");
		types.add("90000");
		types.add("100000");
		types.add("110000");
		types.add("120000");
		types.add("130000");
		types.add("140000");
		types.add("150000");
		types.add("160000");
		types.add("170000");
		types.add("180000");
		types.add("190000");
		types.add("200000");
		types.add("220000");
		types.add("970000");
		types.add("990000");
		String url = "https://restapi.amap.com/v3/place/text?key=" + apiKey;
		String typesStr = "";
		for(int i = 0,s = types.size();i < s;i++){
			String ts = types.get(i);
			if(i != 0){
				typesStr += "|";
			}else {
				typesStr = "&types=";
			}
			typesStr += ts;
		}
		url += typesStr;
		url += "&keywords=" + keyword;
		List<Map<String,Object>> poiList = new ArrayList<>();
		//	请求地图api
		URL urlO = new URL(url);
		URI uri = new URI(urlO.getProtocol(), urlO.getHost(), urlO.getPath(), urlO.getQuery(), null);
		String resStr = HttpRequestHelper.get(uri);
		if(resStr != null){
			JSONObject jsonObject = JSONObject.parseObject(resStr);
			String status = jsonObject.getString("status");
			if("1".equals(status)){
				// 表示请求成功
				JSONArray JApois = jsonObject.getJSONArray("pois");
				for (int i = 0,s = JApois.size();i < s;i++){
					try {
						JSONObject poi = JApois.getJSONObject(i);
						//	地点坐标点
						String poiLoc = poi.getString("location");
						// 格式化为经纬度信息
						String[] poiLocArr = poiLoc.split(",");
						String poiLng = poiLocArr[0];
						String poiLat = poiLocArr[1];
						String id = poi.getString("id");
						//	公司名
						String name = poi.getString("name");
						//	坐标地址
						String pname = poi.getString("pname");
						String cityname = poi.getString("cityname");
						String adname = poi.getString("adname");
						String address = poi.getString("address");
						// 详细地址
						String addrDetail = pname + cityname + adname + address;
						Map<String,Object> poiMap = new HashMap<>();
						poiMap.put("lng",poiLng);
						poiMap.put("lat",poiLat);
						poiMap.put("id",id);
						poiMap.put("name",name);
						poiMap.put("address",addrDetail);
						poiList.add(poiMap);
					} catch (Exception e) {
						log.error("格式化高德地图POI出错:");
						e.printStackTrace();
						continue;
					}
				}
			}
		}
		return poiList;
	}
}
